﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HB.Base
{
    [Serializable]
    public class ActionResult
    {
        public ActionResult SetErrorIf(bool b, string msg)
        {
            if (b)
            {
                SetError(msg);
            }
            return this;
        }
        /// <summary>
        /// Error
        /// </summary>
        /// <param name="msg"></param>
        public ActionResult SetError(string msg)
        {
            IsSuccess = false;
            ErrorMsg = msg;
            return this;
        }
        /// <summary>
        /// 是否正确
        /// </summary>
        public bool IsSuccess { get; protected set; } = true;
        /// <summary>
        /// 错误信息
        /// </summary>
        public string ErrorMsg { get; protected set; }
        public bool Check(params ActionResult[] ar)
        {
            foreach (var item in ar)
            {
                Check(item.ErrorMsg, () => item.IsSuccess);
            }
            return IsSuccess;
        }
        public bool Check(Func<ActionResult> f)
        {
            if (IsSuccess)
            {
                var r = f.Invoke();
                Check(r);
            }
            return IsSuccess;
        }
        public bool Check(string errMsg, Func<bool> fun)
        {
            if (IsSuccess)
            {
                IsSuccess = fun.Invoke();
                if (!IsSuccess)
                {
                    ErrorMsg = errMsg;
                }
            }
            return IsSuccess;
        }
        public bool CheckIf(bool condition, string errMsg, Func<bool> fun)
        {
            if (condition)
            {
                return Check(errMsg, fun);
            }
            return IsSuccess;
        }
       

      
    }
    /// <summary>
    /// 操作返回值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable]
    public class ActionResult<T> : ActionResult
    {
        public ActionResult() { }
        /// <summary>
        /// Success
        /// </summary>
        /// <param name="value"></param>
        public ActionResult(T value)
        {
            SetValue(value);
        }
        /// <summary>
        /// Success
        /// </summary>
        /// <param name="value"></param>
        public ActionResult<T> SetValue(T value)
        {
            if (IsSuccess)
            {
                Result = value;
                ErrorMsg = null;
            }
            return this;
        }
        public T Result { get; set; }

    }
}
